import React, {
  ReactElement,
  useState,
  useEffect,
  forwardRef,
  useImperativeHandle,
  useRef
} from 'react';
import { View, Text } from 'react-native';

import styles from './style';
import { secondToMinute } from '../../../../util/transformDate';
import Log from '../../../../common/log';

const TAG = 'ProblemTimer';

interface ProblemTimeProps {
  time: number;
  action: () => void;
  title: string;
  updateTime?: (time: number) => void;
}

const Timer = (
  { time, action, title, updateTime }: ProblemTimeProps,
  ref: any
): ReactElement => {
  const [remainingTime, setRemainingTime] = useState(Math.round(time / 1000));
  const pauseTimer = useRef(false);

  useEffect((): (() => void) => {
    let timer: NodeJS.Timer | null;

    const clearTimer = (): void => {
      if (timer) {
        Log.i(TAG, JSON.stringify({ event: 'timerEnd', time, title }));
        clearInterval(timer);
        timer = null;
      }
    };

    if (time > 0) {
      let remain = Math.round(time / 1000);
      Log.i(TAG, JSON.stringify({ event: 'timerStart', time, title, remain }));
      timer = setInterval((): void => {
        if (pauseTimer.current) return;
        if (remain === 0) {
          if (action) {
            Log.i(
              TAG,
              JSON.stringify({ event: 'timerEndAction', time, title })
            );
            action();
          }
          clearTimer();
          return;
        }
        remain -= 1;
        setRemainingTime(remain);
        if (updateTime) {
          updateTime(remain);
        }
      }, 1000);
    }
    return (): void => {
      clearTimer();
    };
  }, [action, time, title, updateTime]);

  useImperativeHandle(ref, (): { [key: string]: any } => {
    return {
      pause: (): void => {
        pauseTimer.current = true;
      },
      start: (): void => {
        pauseTimer.current = false;
      }
    };
  });

  return (
    <View style={styles.container}>
      <Text style={[styles.desc, remainingTime <= 5 ? styles.alert : {}]}>
        {title}
      </Text>
      <Text
        style={[styles.time, remainingTime <= 5 ? styles.alert : {}]}
        numberOfLines={1}
      >
        {secondToMinute(remainingTime)}
      </Text>
    </View>
  );
};

export default forwardRef(Timer);
